<?php

require_once("header.php");

$email = $_POST['register-email'];
$nickname = $_POST['nickname'];
$password = $_POST['register-password'];
$year = $_POST['birth'];
$country = $_POST['country'];
$gender = $_POST['gender'];

if ( !preg_match("/^[-\w]+(\.[-\w]+)*@[-\w]+(\.[-\w]+)*(\.[a-z]{2,3})$/i", $email) ) {
	echo 'Please input valid email';
	exit(0);
}
if ( !preg_match("/^.{5,30}$/", $password) ) {
	echo 'Please input valid password';
	exit(0);
}
if ( !preg_match("/^.{1,20}$/", $nickname) ) {
	echo 'Please input nickname';
	exit(0);
}
if ( !preg_match("/^(19[0-9]{2}|200[0-9])$/", $year) ) {
	echo 'Please input year of birth';
	exit(0);
}
if ( !preg_match("/^(1|2)$/", $gender) ) {
	echo 'Please choose gender';
	exit(0);
}
if ( !preg_match("/^(1?[0-9]{1,2}|2[01][0-9])$/", $country) ) {
	echo 'Please choose country';
	exit(0);
}

// check conflict email
$result = $db->query("SELECT user_id FROM user WHERE email='$email'");
if( $result->rowCount() > 0 ) {
	echo 'Email already registered';
	exit(0);
}

// insert new user
$new = $db->query("Insert Into user(email, gender, is_banned, is_admin, nickname, password, birthyear, country_id) values('$email', $gender, 0, 0, '".addslashes($nickname)."', '".md5("Happy".$password)."',$year ,$country )");

if ( $new->rowCount() > 0 ) {

	$id = $db->query("Select user_id As id From user Where email='$email'")->fetch();

	$_SESSION['user_id'] = $id['id'];
	
	$_SESSION['logon'] = true;
	
	echo "OK";
	
} else {

	echo "Something wrong";

}


?>